﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Controls;
using HighLandirect.Applications.ViewModels;
using HighLandirect.Applications.Views;

namespace HighLandirect.Presentation.Views
{
    [Export(typeof(ICustomerView))]
    public partial class CustomerView : UserControl, ICustomerView
    {
        private readonly HashSet<ValidationError> errors = new HashSet<ValidationError>();


        public CustomerView()
        {
            InitializeComponent();
            Validation.AddErrorHandler(this, ErrorChangedHandler);
            this.CustName.TextCapturedPreferredConversion = Microsoft.International.Windows.Controls.PreferredConversion.ToHiragana;
        }


        private CustomerViewModel ViewModel { get { return DataContext as CustomerViewModel; } }


        public void FocusFirstControl()
        {
            CustName.Focus();
        }

        private void ErrorChangedHandler(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                errors.Add(e.Error);
            }
            else
            {
                errors.Remove(e.Error);
            }

            ViewModel.IsValid = !errors.Any();
        }

        private void CustName_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Furigana.Text = this.CustName.TextCaptured;
        }

        private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            this.PostalCD.Select(this.PostalCD.Text.Length, 0);
            if (this.PostalCD.Text.Length < 8) return;

            this.ViewModel.SetJusho(this.PostalCD.Text);

            //続けて番地を入力できるよう、フォーカスとカーソル位置を操作
            this.Address1.Focus();
            this.Address1.Select(this.Address1.Text.Length, 0);
        }

    }
}
